<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Templates</title>
  <meta
 content="C++ Tutorial: Templates"
 name="description" />
  <meta
 content="C++ Tutorial, Function Templates, Generic Functions, Class Templates, Instantiation, 
Template Specialization, Implicit Instantiation, typename, value"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">
<br />
<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>


<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial -   Templates</span></div>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>


<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />
<br />
<img src="images/templates/WalChoolSanA.png" alt="WalChoolSanA"/>
<br />
<br />
<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="Templates">Templates</div>
<p>We use <strong>templates</strong> when we need functions/classes that apply the same algorithm to a several types. So we can use the same function/class regardless of the types of the argument or result. Such a function/class is called a <strong>generic function/class</strong>, and the ability to use and create generic functions/classes is one of the key features of C++. </p>  
<p>The syntax is:
<pre>
template &lt;class T&gt; function_declaration;
</pre>
or
<pre>
template &lt;typename T&gt; function_declaration;
</pre>
</p>
<p>We can use either of them. They are not different since both expressions have exactly the same meaning 
and behave exactly the same way.</p>
<p>Templates are the foundation of generic programming. Generic programming relies on polymorphism. 
Though there are several differences between OOP (class hierarchies and virtual functions) and generic programming (templates),
 the major difference is:</p>
<ul>
     <li><strong>Generic (templates)</strong> : compile time resolution. <br />
	The choice of function invoked when we use is determined by the compiler at compile time.
     </li>
     <li><strong>OOP (virtual functions)</strong> : run time resolution. 
     </li>
</ul>
<p>Generic programming lets us write classes and functions that are polymorphic across unrelated types at compile time.
 A single class or function can be used to manipulate objects of a variety of types. 
The standard library containers, iterators, and algorithms are examples of generic programming. 
We can use library classes and functions on any kind of type.</p>
<p>When we parameterize a class, we get a <strong>class template</strong>, and when we parameterize a function, 
we get a <strong>function template</strong>.</p> 
<br />
<br />


<div class="subtitle" id="FunctionTemplates">Function Templates</div>
<p>Here is a simple example of how we use the template for a function which gives us the minimum value.</p>
<pre>
#include &lt;iostream&gt;

template &lt;class T&gt;
const T& min(const T& a, const T& b) {
	return a < b ? a : b;
}

int main() 
{
	int x = 10, y = 20;
	long xLong = 100, yLong = 200;
	int minimum = min&lt;int&gt;(x, y);
	long minimumLong = min&lt;long&gt;(xLong,yLong);
	std::cout << "minimum = " << minimum << std::endl;
	std::cout << "minimumLong = " << minimumLong << std::endl;
}
</pre>
<p>A function template can be declared <strong>inline</strong> in the same way as a nontemplate function. 
The specifier is placed following the template parameter list and before the return type. It shouldn't be placed 
in front of the <strong>template</strong> keyword. So, it looks like this:</p>
<pre>
template &lt;class T&gt;
<font color="red">inline</font> const T& min(const T& a, const T& b) {
</pre>
<p>But not this:</p>
<pre>
<font color="red">inline</font> template &lt;class T&gt;
const T& min(const T& a, const T& b) {
</pre>
<p>We can also define function templates that accept more than one type parameter, simply by specifying more template parameters between the angle brackets as in the example below.</p>
<pre>
template &lt;class T, class U&gt;
inline const T& min(const T& a, const U& b) {
	return a < b ? a : b;
}
</pre>
<br />
<br />


<div class="subtitle" id="ClassTemplates">Class Templates</div>
<p>Class can be generic using template.</p>
<pre>
template &lt;class T&gt;
class Complx {
private:
	T real, imag;
public:
	Complx(T&, T&);
	T& getReal();
	T& getImag();
};

template &lt;class T&gt;
Complx&lt;T&gt;::Complx(T& a, T& b) {
	real = a;
	imag = b;
}

template &lt;class T&gt;
T& Complx&lt;T&gt;::getReal() {
	return real;
}

template &lt;class T&gt;
T& Complx&lt;T&gt;::getImag() {
	return imag;
}

#include &lt;iostream&gt;

int main() 
{
	double i=100, j=200;
	Complx &lt;double&gt; myComplx(i,j);

	std::cout <<"My complex is " << myComplx.getReal() << ","
		<< myComplx.getImag() << std::endl;
}
</pre>
<br />
<br />

<div class="subtitle" id="nontype">Nontype Template Parameters</div>
<p>We can use a parameter which is not a type. 
This nontype parameter is replaced by value when the function is called.
The type of that value is specified in the template parameter list.
In the example below, the function template declares <strong>arrayInit</strong> as a function template
with one type and one nontype template parameter. The function itself takes a single parameter, which is a reference to an array.
</p>
<pre>
template &lt;class T, <font color="red">size_t N</font>&gt;
void arrayInit(T (&a)[N]) 
{
	for (size_t i = 0; i != N; ++i) a[i] = 0;
}

int main() 
{
	int i[10];
	double d[20];
	arrayInit(i);	// arrayInit(int(&)[10]
	arrayInit(d);	// arrayInit(double (&)[20]
}
</pre>
<p>A template nontype parameter is a constant value inside the template definition. 
We can use a nontype parameter when we need constant expressions. In the example, we need that to specify the size of an array.
So, when <strong>arrayInit</strong> is called, the compiler figures out the value of the nontype parameter 
from the array argument.</p>
<br />
<br />

<div class="subtitle" id="templateparameters">Template Parameters</div>
<p>The name used for a template parameter has not intrinsic meaning. In the previous example, the <strong>min()</strong>'s
template name <strong>T</strong> could be anything:</p>
<pre>
template &lt;class DontCare&gt;
const DontCarer& min(const DontCare& a, const DontCare& b) { return a < b ? a : b; } 
</pre>
<p>But we need to know whether the parameter is a <strong>type</strong> parameter or a <strong>nontype</strong> parameter. 
If it is a type parameter, then we know that the parameter represents an as yet unknown <strong>type</strong>. 
If it is a nontype parameter, we know it is an yet unknown <strong>value</strong>.</p>
<br />

<div class="subtitle_2nd" id="templateparameterscope">Scope of Template Parameter</div>
<pre>
<font color="red">typedef float T;</font>
template &lt;class T&gt;
T& min(const T& a, const T& b) 
{ 
	T tmp = a < b ? a : b; 
	return tmp;
} 
</pre>
<p>The global typedef that defines <strong>T</strong> as <strong>float</strong> is hidden by the type parameter 
named <strong>T</strong>. So, <strong>tmp</strong> is not a <strong>float</strong>, it still has the type of 
the template parameter <strong>T</strong>, not that of the global typedef. In other words, the type of <strong>tmp</strong> 
is whatever type gets bound to the template parameter <strong>T</strong>.</p>
<br />

<div class="subtitle_2nd" id="restrictionstemplateparameter">Template Parameter Name</div>
<p>A name used as a template parameter may not be reused within the template:</p>
<pre>
template &lt;class T&gt;
T& min(const T& a, const T& b) 
{ 
	<font color="red">typedef float T;</font>  // error: redeclaration of template parameter T
	T tmp = a < b ? a : b; 
	return tmp;
} 
</pre>
<p>So, the name of a template parameter can be used only once within the same template parameter list:</p>
<pre>
// error: illegal reuse of template parameter name T
template &lt;class T, classT&gt;
T& min(const T& a, const T& b) 
</pre>
<p>In a function template parameter list, the keywords <strong>typename</strong> and <strong>class</strong> can be 
used interchangeably. But when want to use types inside a function template, we must tell the compiler that 
the name we are using refers to a <strong>type</strong>. We must be explicit because the compiler cannot tell when a 
name defined by a type parameter is a <strong>type</strong> or a <strong>value</strong>:</p>
<pre>
template &lt;typename T&gt;
void foo(const T& vector)
{
	<font color="red">T::const_iterator* it;</font>
}
</pre>
<p>This appears that we're declaring <strong>it</strong> as a pointer to a <strong>T::const_iterator</strong>.  
It's because we know that <strong>T::const_iterator</strong> is a <strong>type</strong>. But what if <strong>T::const_iterator</strong> 
isn't a <strong>type</strong>? 
<p>If <strong>T::const_iterator</strong> is a <strong>type</strong>, then the line is a <strong>declaration</strong>. But 
if <strong>T::const_iterator</strong> is an <strong>object</strong>, then it's a <strong>multiplication</strong>. 
We know that <strong>const_iterator</strong> must be a member of the type bound to <strong>T</strong>, but 
we do not know whether <strong>const_iterator</strong> is the name of a <strong>type</strong> or a <strong>data</strong> 
member. Until <strong>T</strong> is known, there's no way to know whether <strong>T::const_iterator</strong> is 
a type or isn't. When the template <storng>foo</strong> is parsed, <strong>T</strong> isn't known. 
The compiler, by default, assumes that it's a member not <strong>type</strong>. In other words, <strong>T::const_iterator</strong> 
is assumed to <strong>not</strong> be a <strong>type</strong>.</p>
<p>So, if we want the compiler to treat <strong>const_iterator</strong> as a type, then we must explicitly tell 
the compiler to do so:</p>
<pre>
template &lt;typename T&gt;
void foo(const T& vector)
{
	<font color="red">typename</font> T::const_iterator* it;
}
</pre>
<p>By writing <strong>typename T::const_iterator</strong>, we indicate that member <strong>const_iterator</strong> of the type bound to <strong>T</strong> is the name of a type.</p>
<p>Scott Meyers called a variable like <strong>T::const_iterator</strong> a <strong>nested dependent type name</strong>. 
So, the general rule is: anytime we refer to a nested dependent type name in a template, we must immediately precede it by 
the word <strong>typename</strong>.</p>
<p>Let's look at another example of <strong>typename</strong>:</p>
<pre>template&lt;typename T&gt;
void foo(T it)
{
	<font color="red">typename iterator_traits&lt;T&gt;::value_type</font> tmp(*it);
}
</pre>
<p>It declares a local variable, tmp, 
which is the same type as what <strong>T</strong> objects point to, and it initializes <strong>tmp</strong> with the 
object that <strong>T</strong> points to. So, if <strong>T</strong> is <strong>list&lt;string&gt;iterator</strong>, <strong>tmp</strong> 
is of type <strong>string</strong>.</p>
<p>Let's talk about the <strong>iterator_traits</strong>. When we write a generic code, we may need the type of elements to which the iterator refers. So, C++ STL provides a special template structure to define the <strong>iterator_traits</strong>. This structure has information regarding an iterator. It is used as a common interface for all the type definitions an iterator should have, such as the category, the type of the elements, and so on:</p>
<pre>
template &lt;class T&gt;
struct iterator_traits {
     typedef typename T::value_type         value_type;
     typedef typename T::difference_type    difference_type
     typedef typename T::iterator_category  iterator_category  
     typedef typename T::pointer            pointer;
     typedef typename T::reference          reference;
};
</pre>
<p>Here, <strong>T</strong> stands for the type of the iterator. So, the following expression yields the <strong>value type</strong> of iterator type <strong>T</strong>:</p>
<pre>
typename std::iterator_traits&lt;T&gt;::value_type
</pre>
<p><strong>iterator_traits</strong> is so named because it describes argument's proterty/traits. The most important feature of traits templates is that they provide us a way to assocaite information with a type <strong>non-intrusively</strong>. In other words, if we have a new package of code which gives us some iterator-like types called <strong>iter_like</strong> that refers to a <strong>double</strong>, we can assign it a <strong>value_type</strong> without any disturbance to our existing code. All we have to to is add an explicit specialization of <strong>iterator_traits</strong>, and <strong>foo()</strong> will see the type <strong>double</strong> when it asks about the <strong>value_type</strong> of new package's iterator:</p>
<pre>
namespace std
{
     template&lt;&gt;
     struct iterator_traits&lt;<font color="red">NewPackage::iter_like</font>&gt;
     {
         <font color="red">typedef double value_type;</font>
         ...
     };
}
</pre>
<p>This non-intrusive aspect of traits is exactly what makes <strong>iterator_traits</strong> work for pointers: the standard library contains the following <strong>partial</strong> specialization of <strong>iterator_traits</strong>:</p>
<pre>
template &lt;class T&gt;
struct iterator_traits&lt;T*&gt; 
{
      typedef T                               value_type;
      typedef ptrdiff_t                       difference_type;
      typedef random_access_iterator_tag      iterator_catogory;
      typedef T*                              pointer;
      typedef T&                              reference;        
}
</pre>
<p>So, for any type <strong>T*</strong>, it is defined that it has the random access iterator category, and thanks to the indirection through <strong>iterator_traits</strong>, generic functions can now access an iterator's associated types uniformly, whether or not it is a pointer.</p>
<br />
<p>Here is the summary:</p>
<ul>
	<li>When declaring template parameters, <strong>class</strong> and <strong>typename</strong> are interchangeable.</li>
	<li>Use <strong>typename</strong> to identify nested dependent type names.</li>
	<li>If there is any doubt as to whether <strong>typename</strong> is necessary to indicate that a name is 
a type, just specify it. There is not harm in specifying <strong>typename</strong> before a type.</li>
</ul>
<br />
<br />

<div class="subtitle" id="Instantiation">Instantiation</div>
<p>Template is not itself a class or a function, it is a <strong>blueprint</strong>. The compiler uses the 
template to generate type-specific versions. The process of generating a type-specific instance of a template is 
knows as <strong>instantiation</strong>. A template is instantiated when we use it: A class template is 
instantiated when we refer to an actual template class type, and a function template is instantiated when we call 
it or use it to initialize or assign to a pointer to function.</p>
<p>When we write
<pre>
vector&lt;double&gt; vd;
</pre>
<p>the compiler automatically creates a class named <strong>vector&lt;double&gt;</strong>. 
In effect, the compiler creates the <strong>vector&lt;double&gt;</strong> class by rewriting the <strong>vector</strong> 
template, replacing every occurrence of the template parameter <strong>T</strong> by the type <strong>double</strong>.</p>
<pre>
template&lt;class T&gt; 
class vector
{
	int sz;
	T* element;
public:
	vector():size(0), element(0) {}
	~vector() { delete[] element; }
	vector &operator=(const vector&);
	const T& operator[](int n){ return element[n]; }
	void push_back(const T&d);
      ...
};	
</pre>
<br />
<br />

<div class="subtitle" id="TemplateSpecialization">Template Specialization</div>
<p>It is not always possible to write a single template that is for every possible template argument 
with which the template might be instantiated. Because general definition might not compile or might do the wrong thing, 
we may be able to take advantage of some specific knowledge about a type to write a more efficient function 
than the one that is instantiated from the template.</p>
<p>If we want to implement different template when a specific type is passed as template parameter, we can declare a <strong>specialization</strong> of that template.</p>
<p>For example, let's suppose that we have a very simple class called <strong>DoublePlay</strong> that can store one element of any type and that it has just one member function called <strong>doubleIt</strong>, which doubles its value. But we find that when it stores an element of type <strong>string</strong> it would be more convenient to have a completely different implementation with a function member <strong>mine</strong>, so we decide to declare a class template specialization for that type</p>
<pre>
#include &lt;iostream&gt;
#include &lt;string&gt;

template &lt;class T&gt;
class DoublePlay {
private:
	T mine;
public:
	DoublePlay(T& a): mine(a){}
	T doubleIt(){
		return mine*2;
	}
};

<font color="red">template &lt;&gt;
class DoublePlay &lt;std::string&gt; </font>{
private:
	std::string mine;
public:
	DoublePlay(std::string& a):mine(a){}
	std::string& doubleIt(){
		return mine.append(mine);
	}
};

int main() 
{
	int i = 10;
	std::string s="ab";

	DoublePlay&lt;int&gt;myPlayA(i);
	DoublePlay&lt;std::string&gt;myPlayB(s);

	std::cout << i << " to " << myPlayA.doubleIt() << std::endl;
	std::cout << s << " to " << myPlayB.doubleIt() << std::endl;
}
</pre>
<p>Output is:</p>
<pre>
10 to 20
ab to abab
</pre>
<p>The syntax we used in the class template specialization:
<pre>
template <> class mycontainer <std::string> { ... };
</pre>
<p>Notice that we precede the class template name with an empty <strong>template&lt;&gt; </strong>parameter list. This is to explicitly declare it as a template specialization. In other words, the <strong>template&lt;&gt;</strong> in declarations distinguish between the explicit <strong>instantiation</strong> and the explicit <strong>specialization</strong>.</p>
<p>Actually, to extend our understanding of templates, we need to investigate the term <strong>instantiation</strong> and <strong>specialization</strong>. Including a function template in our code does not in itself generate a function definition. It's merely a plan for generating a function definition. When the compiler uses the template to generate a function definition for a particular type, the result is termed an <strong>instantiation</strong> of the template. </p>
<p>In our earlier example, the function call <strong>min(x,y)</strong> causes the compiler to generate an instantiation of <strong>min()</strong>, using <strong>int</strong> as a type. </p>
<p>The template is <strong>not</strong> a function definition, but the specific <strong>instantiation</strong> using <strong>int</strong> is a function definition. This type of instantiation is termed <strong>implicit instantiation</strong> because the compiler deduces the necessity for making the definition by noting that the code uses a <strong>min()</strong> function with <strong>int</strong> parameters.</p>
<p>But more important than this prefix, is the <strong>&lt;std::string&gt;</strong> specialization parameter after the class template name. This specialization parameter itself identifies the type for which we are going to declare a template class specialization (<strong>string</strong>). Notice the differences between the generic class template and the specialization:</p>
<pre>
template &lt;class T&gt; class DoublePlay { ... };
template &lt;&gt; class DoublePlay &lt;str&gt; { ... };
</pre>
<p>The first line is the generic template, and the second one is the specialization.</p>
<p>When we declare specializations for a template class, we must also define all its members, even those exactly equal to the generic template class, because there is no <strong>inheritance</strong> of members from the generic template to the specialization.
</p>
<p>Here is another example of using template specialization used as a part of <a href="boost.html#boostmpl" target="_blank">template metaprogramming</a>.</p>
<pre>
#include &lt;iostream&gt;

template &lt;int n&gt;
struct Factorial 
{
    enum { value = n * Factorial&lt;n - 1&gt;::value };
};
 
template &lt;&gt;
struct Factorial&lt;0&gt; 
{
    enum { value = 1 };
};
 
int main()
{
	std::cout << "Factorial&lt;5&gt;::value = " << Factorial&lt;5&gt;::value << std::endl;	
}
</pre>
<br />
<br />
<img src="images/templates/WalChoolSanB.png" alt="WalChoolSanB"/>
<br />
<br />


<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL)</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>

</ul>
<br /><br />


<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
